#include <iostream>
#include <vector>
#include <unistd.h>
#include <string>
#include <functional>
#include <pthread.h>
#include <ctime>
#include <signal.h>
#include <cstdlib>
using namespace std;

typedef function<void()> task;
// 线程信息结构体
void handler(int signo) {
    cout << "get a signo: " << signo << endl;
    exit(-1);
}


struct ThreadData
{
    // 构造函数
    ThreadData(const string &name, const uint64_t &ctime, task _task)
        : threadname(name), createtime(ctime), func(_task)
    {
    }

    string threadname;
    uint64_t createtime;
    task func;
};

void Print()
{
    cout << "我是新线程中的一个子任务" << endl;
}

// 新线程
void *ThreadRountine(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        cout << "I am new thread: " << td->threadname << ", createtime: " << td->createtime << endl;
        td->func();
        if (td->threadname == "thread3") {
            int a = 10;
            a /= 0;
        }
        sleep(1);
    }
    return nullptr;
}

int main()
{
    signal(8, handler);
    vector<pthread_t> thread_ids;
    for (int i = 1; i <= 5; i++)
    {
        pthread_t tid;
        char thread_name[64];
        string threadname = "thread" + to_string(i);
        ThreadData *t = new ThreadData(threadname, (uint64_t)time(nullptr), Print);
        snprintf(thread_name, sizeof(thread_name), "thread-%d", i);
        pthread_create(&tid, nullptr, ThreadRountine, t);
        thread_ids.push_back(tid);
        sleep(1);
    }
    if (thread_ids.size() == 5)
    {
        for (auto x : thread_ids)
        {
            cout << x << " ";
        }
        cout << endl;
    }

    // 主线程
    while (true)
    {
        cout << "I am main thread" << endl;
        sleep(1);
    }
    return 0;
}